package listbyorder.access101_200.test127;

import java.util.*;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/9 16:50
 */
public class Solution1 {

    // 单词接龙
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        // 特殊条件判断
        if (!wordList.contains(endWord)) {
            return 0;
        }
        int len = 0;
        Queue<String> queue = new LinkedList<>();
        queue.offer(beginWord);
        boolean isFound = false;
        Set<String> dict = new HashSet<>(wordList);
        Set<String> visited = new HashSet<>();   // 表示已经查找过的元素
        visited.add(beginWord);  // 把起始的元素加入set
        while (!queue.isEmpty()) {
            int size = queue.size();
            Set<String> subVisited = new HashSet<String>();
            for (int i = 0; i < size; i++) {
                String temp = queue.poll();
                // 获得当前字符串的下一个节点
                ArrayList<String> neighbors = getNeighbors(temp, dict);
                for (String neighbor : neighbors) {
                    if (!visited.contains(neighbor)) {
                        subVisited.add(neighbor);
                        // 如果找到了，提前结束
                        if (neighbor.equals(endWord)) {
                            isFound = true;
                            break;
                        }
                        queue.offer(neighbor);
                    }
                }
            }
            // 当前层加了一层
            if (subVisited.size() > 0) {
                len++;
            } else {   // 当前层找不到的时候就退出
                return 0;
            }
            visited.addAll(subVisited);
            // 找到以后，提前结束循环
            if (isFound) {
                len++;
                break;
            }
        }
        return len;
    }

    private ArrayList<String> getNeighbors(String temp, Set<String> wordList) {
        ArrayList<String> ans = new ArrayList<String>();
        char[] chars = temp.toCharArray();
        for (char ch = 'a'; ch <= 'z'; ch++) {
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] == ch) {
                    continue;
                }
                char old_chr = chars[i];
                chars[i] = ch;
                if (wordList.contains(String.valueOf(chars))) {
                    ans.add(String.valueOf(chars));
                }
                chars[i] = old_chr;
            }
        }
        return ans;
    }
}
